/*
  Copyright (c) 2014 Dimitrij Gester

  "Smart RC TX" is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  "Smart RC TX" is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General
  Public License along with "Smart RC TX"; if not, write to the
  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  Boston, MA  02111-1307  USA
*/

package com.codeplex.smartrctx.configurator.main.fragments;

import com.codeplex.smartrctx.configurator.main.FragmentConnection;
import com.codeplex.smartrctx.configurator.main.controller.Setter;

import android.app.Activity;
import android.content.Context;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class EditorActionListener implements OnEditorActionListener, OnFocusChangeListener {
		/**
		 * 
		 */
		private final Activity containerActivity;
		private View containerView;
		private FragmentConnection connection;
		private Setter setter;
		
		public EditorActionListener(FragmentConnection c, Setter s) {
			containerActivity = c.getContainingActivity();
			containerView = c.getContainerView();
			connection = c;
			setter = s;
		}
		
		private void hideKeypad(View v) {
		    InputMethodManager imm = (InputMethodManager)containerActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
		    imm.hideSoftInputFromWindow(containerActivity.getCurrentFocus().getWindowToken(), 0);
		}
		
		@Override
		public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
			boolean retv = false;
			if(actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_NULL) { // enter pressed
				try {
					hideKeypad(view);
					containerView.requestFocus();
					setter.setValue(view.getText().toString());
					connection.onValueChanged(view, view.getText().toString());
					retv = true;
				} catch (Exception e) {
				}
			}
			
			return retv;
		}

		@Override
		public void onFocusChange(View view, boolean hasFocus) {
			if(view instanceof TextView && !hasFocus) {
				TextView t = (TextView) view;
				setter.setValue(t.getText().toString());
				connection.onValueChanged(t, t.getText().toString());
			}
		}
	}